package handles

import (
	"fmt"
	"hawkeye/common/logger"
	"hawkeye/event"
	"hawkeye/protocol"
	"sync"

	"github.com/panjf2000/gnet/v2"
)

// BaseHandler 基础处理器，提供公共方法
type BaseHandler struct {
	connMutex   *sync.RWMutex
	connections map[gnet.Conn]string
}

// SendMessageToConnection 向指定连接发送消息
func (h *BaseHandler) SendMessageToConnection(c gnet.Conn, msg *protocol.Message) error {
	// 设置消息序列号和时间戳
	msg.Sequence = uint64(msg.Timestamp)

	logger.Info("resp data:", msg)
	// 编码消息
	data, err := protocol.EncodeMessage(msg)
	if err != nil {
		return err
	}

	// 发送消息
	_, err = c.Write(data)
	return err
}

// SendMessage 向所有连接发送消息
func (h *BaseHandler) SendMessage(ctx *event.Context, msg *protocol.Message) error {

	// 找到对应的连接并发送响应
	h.connMutex.RLock()
	for conn := range h.connections {
		if ctx.ConnID == conn.RemoteAddr().String() {
			h.connMutex.RUnlock()
			return h.SendMessageToConnection(conn, msg)
		}
	}
	h.connMutex.RUnlock()
	return fmt.Errorf("未找到对应的连接")
}

// updateClientID 更新客户端ID
func (h *BaseHandler) updateClientID(connAddr, clientID string) {
	h.connMutex.Lock()
	defer h.connMutex.Unlock()

	for conn := range h.connections {
		if conn.RemoteAddr().String() == connAddr {
			h.connections[conn] = clientID
			break
		}
	}
}
